<template>
  <div class="home">
    <div class="nav">
      <el-image style="width: 38px;height: 37px;" :src="require('@/assets/images/canteenIcon.png')" />
      <div class="title">饭堂管理/订餐管理</div>
    </div>
    <div class="contentBox">
      <!-- 搜索、选择 -->
      <div class="sousuo">
        <!-- ref="form" :model="form" -->
        <el-form ref="queryForm" :model="queryParams" style="display: flex;flex-wrap: wrap;" label-width="80px">
          <el-form-item label="学校" prop="schoolId">
            <el-select v-model="queryParams.schoolId" placeholder="请选择学校" clearable>
              <el-option v-for="(item, index) in schoolList" :key="item.id" :label="item.name"
                :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="班级" prop="classId">
            <el-select v-model="queryParams.classId" placeholder="请选择班级" clearable>
              <el-option v-for="item in classList" :key="item.id" :value="item.id" :label="item.name" />
            </el-select>
          </el-form-item>
          <el-form-item label="学生姓名" prop="studentName">
            <el-input v-model="queryParams.studentName" placeholder="请输入学生姓名" clearable></el-input>
          </el-form-item>
          <el-form-item label="缴费方式" prop="rechargeType">
            <el-select v-model="queryParams.rechargeType" placeholder="请选择缴费方式" clearable>
              <el-option label="微信支付" :value=0></el-option>
              <el-option label="现金支付" :value=2></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="缴费类目" prop="mealType">
            <el-select v-model="queryParams.mealType" placeholder="请选择缴费类目" clearable>
              <el-option label="早餐" :value=0></el-option>
              <el-option label="午餐" :value=1></el-option>
              <!-- <el-option label="晚餐" :value=2></el-option> -->
              <el-option label="早餐、午餐" :value=3></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="日期" prop="datavalue">
            <div class="date">
              <el-date-picker v-model="queryParams.datavalue" value-format="yyyy-MM-dd" type="daterange"
                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change="selectDate">
              </el-date-picker>
            </div>
          </el-form-item>
          <el-form-item>
            <div style="display: flex;">
              <div class="btn1"><el-button type="primary" @click="handleQuery">查询</el-button></div>
              <div class="btn2"><el-button type="primary" @click="resetQuery">重置</el-button></div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <!-- 订餐情况 -->
      <div class="crderingmeals">
        <div class="mealsNumber">
          <div class="div">订餐人数: <span>{{ orderingPeopleNumber.totalNum }}</span> 人</div>
          <div class="div">早餐: <span>{{ orderingPeopleNumber.breakfastNum }}</span> 人</div>
          <div>午餐: <span>{{ orderingPeopleNumber.lunchNum }}</span> 人</div>
        </div>
        <div class="btnbox">
          <div class="btn">
            <el-image style="width: 26px;height: 26px; margin-right: 10px;"
              :src="require('@/assets/images/addIcon.png')"></el-image>
            <el-button type="warning" round @click="handleAdd">添加</el-button>
          </div>
          <div class="btn">
            <el-image style="width: 27px;height: 23px;margin-right: 10px;"
              :src="require('@/assets/images/daoruIcon.png')"></el-image>
            <el-button type="warning" round @click="handleExport">导出</el-button>
          </div>
          <div class="btn">
            <el-image style="width: 27px;height: 24px;margin-right: 10px;"
              :src="require('@/assets/images/xiazaiIcon.png')"></el-image>
            <el-button type="warning" round @click="handleImport">导入</el-button>
          </div>
        </div>
      </div>
      <!-- 表格 -->
      <div class="tableBox">
        <el-table border v-loading="loading" :data="orderingList" :max-height="640" stripe>
          <el-table-column :resizable="false" type="index" align="center" label="序号" />
          <el-table-column :resizable="false" label="学校名称" align="center" prop="schoolName" />
          <el-table-column :resizable="false" label="年级" align="center" prop="gradeName" />
          <el-table-column :resizable="false" label="班级" align="center" prop="className" />
          <el-table-column :resizable="false" label="学生姓名" align="center" prop="studentName" />
          <el-table-column :resizable="false" label="学生证件号" align="center" prop="identityNumber" />
          <el-table-column :resizable="false" label="家长手机号" align="center" prop="parentMobile" />
          <el-table-column :resizable="false" label="缴费项目" align="center" prop="feeItemName" />
          <el-table-column :resizable="false" label="缴费类目" align="center" prop="mealType">
            <template slot-scope="scope">
              <div v-if="scope.row.mealType == 0">早餐</div>
              <div v-else-if="scope.row.mealType == 1">午餐</div>
              <div v-else-if="scope.row.mealType == 2">晚餐</div>
              <div v-else>早餐、午餐</div>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="餐数" align="center" prop="meals" />
          <el-table-column :resizable="false" label="已交金额" align="center" prop="totalFee" min-width="100">
            <template slot-scope="scope">
              <div>{{ scope.row.totalFee }}元 (已退:{{scope.row.returnFee}}元)</div>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="饭堂收款" align="center" prop="totalFee">
            <template slot-scope="scope">
              <div>{{ scope.row.totalFee }}元</div>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="缴费方式" align="center" prop="rechargeType">
            <template slot-scope="scope">
              <div v-if="scope.row.rechargeType == 0">微信支付</div>
              <div v-else-if="scope.row.rechargeType == 2">现金支付</div>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="缴费时间" align="center" prop="feeTime" />
          <el-table-column :resizable="false" label="操作" align="center">
            <template slot-scope="scope">
              <el-button class="btn" @click="openDrawer(scope.row)" type="text">详情</el-button>
              <!-- <el-button style="color: #000;" type="text">编辑</el-button>
              <el-button type="text">删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" @pagination="getListData" />
      </div>
    </div>
    <!-- 添加 -->
    <el-dialog title="添加" width="500px" :visible.sync="open" append-to-body>
      <el-form ref="form" :rules="rules" :model="form" label-width="100px">
        <el-form-item label="年级" prop="gradeId">
          <el-select v-model="form.gradeId" placeholder="选择年级" clearable @change="changeGrade">
            <el-option v-for="(item , index) in gradeList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级" prop="classId">
          <el-select v-model="form.classId" placeholder="选择班级" clearable>
            <el-option v-for="(item , index) in classList2" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学生姓名" prop="studentName">
          <el-input v-model="form.studentName" placeholder="输入学生姓名" clearable/>
        </el-form-item>
        <el-form-item label="学生证件号" prop="identityNumber">
          <el-input v-model="form.identityNumber" placeholder="输入学生证件号" maxlength="18" clearable/>
        </el-form-item>
        <el-form-item label="家长手机号" prop="parentsPhone">
          <el-input v-model="form.parentsPhone" placeholder="请输入家长手机号" :maxlength="11" clearable/>
        </el-form-item>
        <el-form-item label="缴费方式" prop="rechargeType">
          <el-select v-model="form.rechargeType" placeholder="选择缴费方式" clearable>
            <el-option label="现金" :value=2></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="餐费类型" prop="mealType">
          <el-select v-model="form.mealType" placeholder="选择餐费类型" clearable>
            <el-option label="早餐" :value=0></el-option>
            <el-option label="午餐" :value=1></el-option>
            <el-option label="早餐、午餐" :value=3></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="支付金额" prop="payAmount">
          <el-input v-model="form.payAmount" placeholder="请输入金额" clearable/>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- drawer -->
    <el-drawer title="详情" :visible.sync="drawer" direction="rtl" size="732px">
      <div class="drawercontent" v-loading="loadingDrawer">
        <div class="line"></div>
        <div class="item" v-for="(item, index) in drawerData" :key="index">
          <span class="title">{{ item.title }} <div class="line"></div></span>
          <div style="margin-top: 10px;">
            <el-descriptions v-for="(item1, index1) in item.list" :key="index1" :border="true" :column="1"
              :labelStyle="{ width: '130px', textAlign: 'center', color: '#000' }" :contentStyle="{ color: '#000' }">
              <el-descriptions-item :label="item1.lable" v-if="item1.lable == '合计金额' || item1.lable == '合计缴费'">{{ item1.name
                }}元</el-descriptions-item>
              <el-descriptions-item :label="item1.lable" v-else-if="item1.lable == '订餐数' || item1.lable == '订餐总数'">{{
        item1.name
      }}餐</el-descriptions-item>
              <el-descriptions-item :label="item1.lable" v-else>{{ item1.name }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </div>
      </div>
    </el-drawer>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-form ref="Form" :model="uploadform"  label-width="50px">
<!--        <el-form-item label="年级" prop="gradeId">-->
<!--          <el-select v-model="uploadform.gradeId" clearable @change="changeGrade">-->
<!--            <el-option v-for="item in gradeList" :key="item.id" :value="item.id" :label="item.name">-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="班级" prop="classId">-->
<!--          <el-select v-model="uploadform.classId" clearable>-->
<!--            <el-option v-for="item in classList2" :key="item.id" :value="item.id" :label="item.name">-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
      </el-form>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?gradeId=' + uploadform.gradeId + '&classId=' + uploadform.classId"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <!-- <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据 -->
        </div>
        <div class="el-upload__tip" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！
          <el-link href="https://ydzs.mjunity.com/ydzs/profile/2024/06/15/饭堂订餐线下缴费导入模板.xlsx" type="danger" style="font-size:12px;color: red;">下载模板</el-link>
          <!-- <el-link type="danger" style="font-size:12px;color: red;" @click="importTemplate">下载模板</el-link> -->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!--导入结果-->
    <el-drawer title="导入结果" size="40%" :visible.sync="openMsg" direction="rtl" :before-close="handleClose">
      <div style="padding: 20px;">
        <div>导入总数：{{ importData.errorCount + importData.successCount }} 条</div>
        <div style="margin: 10px 0;">导入成功：{{ importData.successCount }} 条</div>
        <div style="margin: 0px 0 10px;"> <span style="color:red">导入失败：</span> {{ importData.errorCount }} 条</div>
        <el-table border :data="newimportDataList" style="width: 100%">
          <el-table-column
          :resizable="false"
            align="center"
            type="index"
            label="序号" >
          </el-table-column>
          <el-table-column align="center" :resizable="false" prop="studentName" label="姓名" width="80">
          </el-table-column>
          <el-table-column align="center" :resizable="false" prop="identityNumber" label="证件号" width="165">
          </el-table-column>
          <el-table-column align="center" :resizable="false" prop="parentsPhone" label="家长手机号" width="110">
          </el-table-column>
          <!-- <el-table-column align="center" :resizable="false" prop="breakfastAmount" label="早餐缴费金额">
          </el-table-column>
          <el-table-column align="center" :resizable="false" prop="lunchAmount" label="午餐缴费金额">
          </el-table-column>
          <el-table-column align="center" :resizable="false" prop="dinnerAmount" label="晚餐缴费金额">
          </el-table-column> -->
          <el-table-column align="center" :resizable="false" prop="failureResult" label="失败原因" width="450">
          </el-table-column>
        </el-table>
        <pagination
          v-show="importDatatotal>0"
          :total="importDatatotal"
          :page.sync="currentPage"
          :limit.sync="pageSize"
          @pagination="paginatedData"
        />
      </div>
    </el-drawer>
  </div>
</template>
<script>
import { listClasses } from "@/api/classSystem/class";
import { orderingList, orderingDetails, orderingPeopleNumber, orderAdd } from "@/api/canteenSystem/orderingManagement.js";
import { listGrades, getGrades, delGrades, addGrades, updateGrades, getschool } from "@/api/gradeSystem/grade";
import { getToken } from "@/utils/auth";
export default {
  data () {
    return {
      drawer: false,
      // 导入遮罩层结果
      openMsg: false,
      // 导入错误的总条数
      importDatatotal:0,
      // 导入结果
      importData: {},
      importDataList:[],
      newimportDataList:[],
      currentPage: 1,
      pageSize: 10, // 每页显示的数据条数
      // 遮罩层
      open: false,
      loading: true,
      loadingDrawer: true,
      //查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        schoolId: null,
        classId: null,
        mealType: null,
        rechargeType: null,
        studentName: null,
        startDate: null,
        endDate: null,
        datavalue: null
      },
      //订餐数据
      orderingList: [],
      //学校列表
      schoolList: [],
      //班级列表
      classList: [],
      //总条数
      total: 0,
      //订餐人数
      orderingPeopleNumber: {},
      //详情
      drawerData: [],
      // 表单
      form:{},
      // 表达检验
      rules:{
        gradeId:[
          { required: true, message: "年级不能为空", trigger: "blur" },
        ],
        classId:[
          { required: true, message: "班级不能为空", trigger: "blur" },
        ],
        studentName:[
          { required: true, message: "学生姓名不能为空", trigger: "blur" },
        ],
        identityNumber:[
          { required: true, message: "学生证件号不能为空", trigger: "blur" },
          // {pattern:/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])\d{3}[\dXx]$/,message: "请输入有效的18位身份证号", trigger:"change" }
          { pattern: /^[0-9]\d{16}[0-9Xx]$/, message: '请输入有效的18位身份证号' }
        ],
        parentsPhone:[
          { required: true, message: "家长手机号不能为空", trigger: "blur" },
          { pattern: /^[0-9]\d*$/, message: '只能输入数字' }
        ],
        rechargeType:[
          { required: true, message: "缴费方式不能为空", trigger: "blur" },
        ],
        mealType:[
          { required: true, message: "餐费类型不能为空", trigger: "blur" },
        ],
        payAmount:[
          { required: true, message: "支付金额不能为空", trigger: "blur" },
          { pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: '请输入正确的金额格式!例如:0.01' }
        ],
      },
      //添加的年级
      gradeList:[],
      //添加的班级
      classList2:[],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        // updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/wsd_canteens/importOrdering"
      },
      //导入表单参数
      uploadform: {},
    }
  },
  created () {
    this.getschoolList()
    this.getListData()
    this.getclassList()
    this.getGradeList()
  },
  methods: {
    // 查询学校
    async getschoolList () {
      let res = await getschool()
      this.schoolList = res
    },
    /**班级列表**/
    getclassList () {
      let queryParams = {}
      listClasses().then(response => {
        this.classList = response.rows;
      });
    },
    //搜索按钮
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getListData()
    },
    //日期
    selectDate (e) {
      if (e) {
        this.queryParams.startDate = e[0]
        this.queryParams.endDate = e[1]
      }
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.queryParams.startDate = null,
        this.queryParams.endDate = null,
        this.queryParams.datavalue = null
      this.handleQuery();
    },
    // 获取列表数据
    async getListData () {
      // 遮罩层
      this.loading = true
      let res = await orderingList(this.queryParams)
      this.orderingList = res.rows
      this.total = res.total
      let res2 = await orderingPeopleNumber(this.queryParams)
      this.orderingPeopleNumber = res2.data
      this.loading = false

    },
    //打开弹出层
    async openDrawer (data) {
      this.loadingDrawer = true
      this.drawer = true
      let res = await orderingDetails(data.paymentId)
      this.drawerData = res.data
      this.loadingDrawer = false
    },
    // 获取年级
    getGradeList () {
      listGrades(this.queryParams).then(response => {
        this.gradeList = response.rows;
      });
    },
    //添加和导入的年级的选择
    changeGrade(gradeID){
      this.getclassList2(gradeID);
      if (this.form.classId) {
        this.form.classId=null
      }else if (this.uploadform.classId) {
        this.uploadform.classId=null
      }
    },
    //添加和导入的班级
    getclassList2(gradeId) {
      let queryParams = {}
      if (gradeId) {
        queryParams.gradeId = gradeId;
      }else {
        this.classList2 = []
        return
      }
      listClasses(queryParams).then(response => {
        this.classList2 = response.rows;
      });
    },
    // 表单重置
    reset () {
      this.form = {
        id: null,
        name: null,
        classId: null,
        status: null,
        isDeleted: null,
        createTime: null,
        updateTime: null,
        createdBy: null,
        updatedBy: null,
        parentsPhone: null
      };
      this.resetForm("form");
    },
    // 添加按钮
    handleAdd () {
      this.reset();
      this.open = true
    },
    // 提交表单
    submitForm(){
      this.$refs['form'].validate(valid=>{
        if(valid){
          orderAdd(this.form).then(response => {
            this.$modal.msgSuccess("添加成功");
              this.open = false;
              this.getListData();
          })
        }
      })
    },
    // 关闭弹出层
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => { });
    },
     /** 导入按钮操作 */
     handleImport () {
      this.reset();
      this.upload.title = "导入学生信息";
      this.upload.open = true;
    },
    handleExport() {
      //const queryParams = this.queryParams;
      this.download('wsd_canteens/exportOrder', {
        ...this.queryParams
      }, `订餐管理_${new Date().getUTCFullYear()}${new Date().getUTCMonth()}${new Date().getUTCDate()}${new Date().getHours()}${new Date().getMinutes()}.xlsx`)
    },
    /** 下载模板操作 */
    importTemplate () {
      https://ydzs.mjunity.com/ydzs/profile/2024/06/14/865c2a4db619471abdee5392f3b8b200.xlsx
      return
      this.download('honor/honor/importTemplate', {
      }, `导入学生信息模板_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress (event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess (response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      // this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.openMsg = true
      this.importData = response.data
      this.importDataList=response.data.result
      this.paginatedData()
      this.importDatatotal=response.data.result.length
      this.getListData();
    },
    //导入的分页
    paginatedData() {
    const startIndex =(this.currentPage - 1)* this.pageSize;
    const endIndex = startIndex + this.pageSize;
    this.newimportDataList=this.importDataList.slice(startIndex,endIndex)
    // console.log(this.importDataList.slice(startIndex,endIndex));
    },
    // 提交上传文件
    submitFileForm () {
      this.$refs["Form"].validate(valid => {
        if (valid) {
          this.$refs.upload.submit();
        }
      })

    }
  }
}
</script>
<style lang="scss" scoped>
.home {
  padding: 10px;
  box-sizing: border-box;
  background-color: #eee;
  overflow: auto;
}

.nav {
  // width: 1636px;
  width: 98%;
  display: flex;
  align-items: center;
  margin: 10px auto;
  padding-left: 20px;
  box-sizing: border-box;

  .title {
    margin-left: 10px;
    font-weight: bold;
  }
}

.contentBox {
  // width: 1636px;
  width: 98%;
  height: 881px;
  margin: 0 auto;
  padding: 20px;
  box-sizing: border-box;
  background-image: url('../../../assets/images/canteenBJ.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;

  .sousuo {
    ::v-deep .el-input--medium .el-input__inner {
      width: 170px;
    }

    .date {
      ::v-deep .el-range-editor--medium.el-input__inner {
        width: 243px;
      }
    }

    .btn1 {
      ::v-deep .el-button--medium {
        background-image: linear-gradient(to right, #DE0D0F, #F27605);
      }
    }

    .btn2 {
      ::v-deep .el-button--medium {
        background-color: #F5F5F5;
        color: #999999;
        border: 1px solid #999999;
        margin-left: 10px;
      }
    }

  }

  .crderingmeals {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .mealsNumber {
      // width: 30%;
      display: flex;
      justify-content: space-between;

      .div {
        margin-right: 20px;
      }
    }

    .btnbox {
      width: 20%;
      display: flex;
      justify-content: space-between;

      .btn {
        display: flex;
        align-items: center;

        ::v-deep .el-button--medium {
          background-color: #F47D04;
          padding: 5px 10px;
        }
      }
    }
  }

  .tableBox {
    margin-top: 10px;

    .btn {
      color: #fff;
      background-color: #F47D04;
      padding: 5px 10px;
      border-radius: 20px;
    }
  }
}

// drawer
.drawercontent {
  padding: 0 20px 20px;
  box-sizing: border-box;

  .line {
    border: 1px solid #ECECEC;
    width: 100%;
  }

  .item {
    margin-top: 10px;

    .title {
      font-size: 16px;
      font-weight: bold;
      position: relative;
      z-index: 0;

      .line {
        position: absolute;
        top: 12px;
        left: 0;
        z-index: -1;
        width: 100%;
        height: 8px;
        border-radius: 5px;
        background-color: #FFCE80;
      }
    }
  }
}
</style>
